# -*- coding: utf-8 -*-
# @Time : 2022/3/24 17:01
from flask import jsonify
from src.Bugs.Database.bugs_database import BugData, BugDataSchema
from Common.yaml_method import YamlMethod
from sqlalchemy import and_
from sqlalchemy import or_
from Common.mysql import db
from sqlalchemy import func


class BugList:
    """
    获取缺陷列表接口
    """

    @staticmethod
    def bug_list(page, limit, title, project_id, sprint, platform, level, status, handler):
        """
        获取缺陷列表接口
        :param page: 页码
        :param limit: 每页多少条数据
        :param title: 缺陷名称
        :param project_id: 项目ID
        :param sprint: 迭代
        :param platform: 软件平台
        :param level: 缺陷等级
        :param status: 缺陷状态
        :param handler: 责任人/处理人
        :return:
        """

        code = YamlMethod().read_data('code.yaml')['code']
        query = BugData.query

        # 添加必传字段project_id到查询条件
        conditions = [BugData.projectId == project_id, or_(BugData.delete.is_(None), BugData.delete != 1)]
        if title or sprint or platform or level or status or handler:
            if title:
                conditions.append(BugData.title.ilike(f"%{title}%"))
            if sprint:
                conditions.append(BugData.sprint.in_(sprint))
            if platform:
                conditions.append(BugData.platform.in_(platform))
            if level:
                conditions.append(BugData.level.in_(level))
            if status:
                conditions.append(BugData.status.in_(status))
            if handler:
                handler_keywords = handler.get('data_value', [])  # 获取传入的handler关键词列表
                handler_key = handler.get('data_key')  # 获取传入的handler数据键
                if handler_keywords and handler_key:
                    if handler_key == 'handler':
                        # 使用any_和split处理handler字段中包含关键词的情况
                        conditions.append(
                            or_(*[BugData.handler.ilike(f"%{keyword}%") for keyword in handler_keywords])
                        )
                    elif handler_key == 'responsible':
                        conditions.append(
                            or_(*[BugData.responsible.ilike(f"%{keyword}%") for keyword in handler_keywords])
                        )
                    elif handler_key == 'createUser':
                        conditions.append(
                            or_(*[BugData.create_user.ilike(f"%{keyword}%") for keyword in handler_keywords])
                        )

        query = query.filter(and_(*conditions)).order_by(BugData.create_time.desc())

        pagination = query.paginate(page=page, per_page=limit)
        total = pagination.total

        info = []
        for i in pagination.items:
            mysql_schema = BugDataSchema()
            mysql_data = mysql_schema.dump(i)
            # 将单条信息添加到info中
            info.append(mysql_data)

        res = {
            'code': code[0],
            'message': 'success',
            'data': {
                'bugList': info,
                'total': total
            }
        }

        return res

    @staticmethod
    def account_pending(handler):
        """
        统计所有项目待处理缺陷数
        :param handler: 用户名
        :return:
        """

        query_result = db.session.query(BugData.projectId, func.count(BugData.id)).filter(BugData.handler == handler).group_by\
            (BugData.projectId).all()
        result = []
        print(query_result)
        # for project_id, count in query_result:
        #     result.append({
        #         'projectId': project_id,
        #         'count': count
        #     })
        #
        # return jsonify(result)


if __name__ == '__main__':
    BugList().account_pending('admin')


